<template>
  <div class="page">
    <n-form ref="formRef" :model="model" :rules="rules" size="large">
      <n-form-item label="Username" path="username">
        <n-input v-model:value="model.username" type="text" placeholder="请输入用户名" />
      </n-form-item>

      <n-form-item label="Password" path="password">
        <n-input v-model:value="model.password" type="password" placeholder="请输入密码" />
      </n-form-item>

      <n-form-item label="VerifyCode" path="verifyCode">
        <n-input
          v-model:value="model.verifyCode"
          placeholder="图片验证码"
          maxlength="4"
          @keyup.enter="toLogin"
        />
        <!-- 验证码组件 -->
        <Captcha
          ref="captchaRef"
          v-model:value="model.captchaId"
          @change="
            () => {
              model.verifyCode = ''
            }
          "
        />
      </n-form-item>

      <n-form-item>
        <n-button type="primary" @click="toLogin">登录</n-button>
      </n-form-item>
    </n-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInst, FormRules } from 'naive-ui'
import { useStore } from '@/hooks/store'
import Captcha, { type CaptchaInst } from './components/captcha.vue'
import router from '@/router'

const { user } = useStore()

const model = reactive({
  username: 'admin',
  password: '123456',
  captchaId: '',
  verifyCode: ''
})
const rules: FormRules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
}

const formRef = ref<FormInst | null>(null)
const captchaRef = ref<CaptchaInst | null>(null)

/** 登录 */
function toLogin() {
  // 表单校验
  formRef.value?.validate(async (errors) => {
    // 表单校验失败
    if (errors) return

    try {
      // 登录
      await user.login({ ...model })

      // 登录成功
      window.$message.success('登录成功')

      // 跳转首页
      await router.push('/')
    } catch (err) {
      // 刷新验证码
      captchaRef.value?.refresh()

      console.error(err)
    }
  })
}
</script>

<style lang="scss" scoped>
.page {
  box-sizing: border-box;
  height: 100vh;

  .n-form {
    margin: 100px auto;
    padding: 16px;
    width: 360px;
    border-radius: 10px;
    background-color: #ffffff;
  }
}
</style>
